﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Http;

using web_api.Models;

namespace FileUploadExample.Controllers
{
    public class UploadController : ApiController
    {

        //接受上传
        public bool Post()
        {
            var files = HttpContext.Current.Request.Files;
            if (files.Count == 0) return false;//如果没有任何文件被传入，直接返回false
            var file = files[0];
            if (file.ContentLength > 0) //判断文件是否已经接收完毕
            {
                //生成随机文件名
                var rnd = new Random();
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(100, 999) +
                               Path.GetExtension(file.FileName);
                //确定保存路径
                var savePath = HttpContext.Current.Server.MapPath($"~/Updata/{file.FileName}");
                //保存文件
                file.SaveAs(savePath);
                DBhelper.Add(1, file.FileName, newFileName, Path.GetExtension(file.FileName), "~/Updata/");
                return true;
            }
            

            return false;
        }

        //接受下载
   
            public HttpResponseMessage Get(string name)
            {

   
            var path = System.Web.HttpContext.Current.Server.MapPath($"~/Updata/{name}");
                var originName = "class1.cs";
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new FileStream(path, FileMode.Open);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = originName
                };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentLength = stream.Length;
                return result;



             
            }
        }

     
    
}
